var options = [ "infiniteScrolling", "updateEnabled", "showExtraButtons", "postPreview", "reorderTitle", "updateLastForumThreads", "showResetButton", "reorderStreamTitle", "ajaxSubmit", "ajaxEdit", "spoilerLongPosts", "darkStyle", "listenForPM", "hideNews", "jumpToLastPost" ], headlines = [ "hlCs", "hlSc", "hlDota", "hlWc3", "hlLol", "hlOther" ];

function save(btn) {
	var num = function(e) {
		var nums = $F(e);
		if (nums <= 0) {
			$(e).setValue(0);
			nums = 0;
		}
		return nums;
	};

	options.each(function(option) {
		localStorage[option] = $(option).checked;
	});

	localStorage["updateInterval"] = num("updateInterval");
	localStorage["newPostColor"] = $F("newPostColor");
	localStorage["spoilerLongPostsRows"] = num("spoilerLongPostsRows");

	headlines.each(function(headline) {
		localStorage[headline] = $(headline).checked;
	});

	window.location.reload();
}

function initNavigation() {
	if (localStorage["_tab"]) {
		var val = localStorage["_tab"];
		$$("input[type='radio']").each(function(input) {
			if (input.identify() == val) {
				input.checked = true;
			} else {
				input.checked = false;
			}
		});
	}

	$$("input[type='radio']").each(function(input) {
		input.observe("click", function() {
			localStorage["_tab"] = input.identify();
		});
	});
}

function loadDefaultOptions() {
	chrome.extension.sendRequest({
		method : "getOptions"
	});

	localStorage["inited"] = true;

	window.location.reload();
}

function load() {
	if (Object.isUndefined(localStorage["inited"])) {
		loadDefaultOptions();
	}

	initNavigation();

	$("listenForPM").observe("click", function(event) {
		chrome.permissions.request({
			permissions : [ "notifications" ]
		}, function(granted) {
			if (!granted) {
				$("listenForPM").checked = false;
			}
		});
	});

	// load version number from manifest
	new Ajax.Request("../manifest.json", {
		onSuccess : function(r) {
			var manifest = r.responseText.evalJSON();
			$("version").update("(v" + manifest.version + ")");
		}
	});

	options.each(function(option) {
		$(option).checked = localStorage[option] == "true" ? true : false;
	});

	if ($("updateEnabled").checked) {
		$("updateEnabled").up("tr").next("tr").show();
	} else {
		$("updateEnabled").up("tr").next("tr").hide();
	}

	if ($("spoilerLongPosts").checked) {
		$("spoilerLongPosts").up("tr").next("tr").show();
	} else {
		$("spoilerLongPosts").up("tr").next("tr").hide();
	}

	$("updateInterval").setValue(localStorage["updateInterval"]);
	$("spoilerLongPostsRows").setValue(localStorage["spoilerLongPostsRows"]);
	$("newPostColor").setValue(localStorage["newPostColor"] || "#ffff00").setStyle({
		"backgroundColor" : $("newPostColor").value
	});

	headlines.each(function(headline) {
		$(headline).checked = localStorage[headline] == "true" ? true : false;
	});
}
